package com.house.wym.alipay.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.house.wym.entity.House;
import com.house.wym.service.IHouserService;
import com.house.wym.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * 1@Description:
 * @Version: V1.0
 */
@Controller
@Slf4j
@AllArgsConstructor
public class EasyPayController {
    private final Config config;
    private IHouserService houserService;

    @GetMapping("/pay")
    public String pay(@RequestParam("id")String hid,@RequestParam("name")String name,HttpServletRequest request) throws Exception {
        String price=houserService.findPrice(Integer.parseInt(hid));
        request.setAttribute("payprice",price);
        request.setAttribute("hid",hid);
        long seed = System.currentTimeMillis();

        // 使用种子创建随机数生成器
        Random random = new Random(seed);

        // 生成随机数
        int randomNumber = random.nextInt();

        Factory.setOptions(config);
        //调用支付宝接口
        AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate("hid",""+randomNumber, price);
        //解析结果
        String httpBody = response.getHttpBody();
        //转JSON对象
        JSONObject jsonObject = JSONObject.parseObject(httpBody);
        String qrUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
        //生成二维码
        QrCodeUtil.generate(qrUrl,300,300,new File("D://HouseRent-master//src//main//webapp//static//img//pay.jpg"));
        houserService.updateHouseState3(Integer.parseInt(hid));
        return "pay";
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request){
        log.info("收到支付成功通知");
        String out_trade_no = request.getParameter("out_trade_no");
        log.info("流水号：{}",out_trade_no);
        return "paysuccess";
    }

    @GetMapping("/query")
    public String query() throws Exception {
        Factory.setOptions(config);
        AlipayTradeQueryResponse response = Factory.Payment.Common().query("1213131313131");
        return response.getHttpBody();
    }

}
